import { OrderProps, OrderRecommend } from '@/api/order';
import { Button, Field, Icon, Popup, Rate } from '@antmjs/vantui';
import { Text, View } from '@tarojs/components';
import Taro from '@tarojs/taro';
import { useSetState } from 'ahooks';
import { useState } from 'react';
import { useRequest } from 'taro-hooks';
import { TemplateMessage } from 'types/user';

export function useEvaluate(props: {
  onSuccess: Function;
  detail: OrderProps;
}) {
  const [show, setShow] = useState<boolean>(false);

  const [formValues, setFormValues] = useSetState<{
    rate: number;
    remark: string | undefined;
  }>({
    rate: 5,
    remark: undefined,
  });
  const { runAsync, loading } = useRequest(OrderRecommend, { manual: true });

  function renderNode() {
    return (
      <Popup show={show} round style={{ overflow: 'inherit' }}>
        <Icon
          name='close'
          className=' absolute right-0 -top-[90px] text-white text-3xl'
          onClick={() => setShow(false)}
        />
        <View className='w-[630px] px-4 pb-4'>
          <Text className=' py-5 font-bold text-lg block text-center'>
            评价
          </Text>

          <Text className=' text-xs text-gary4 block'>请给这次咨询打分</Text>
          <Rate
            value={formValues.rate}
            onChange={(e) => setFormValues({ rate: e.detail })}
            className=' mt-2'
            color='#F6AD3C'
          />

          <Text className=' text-xs text-gary4 block mt-4'>请输入您的评价</Text>
          <Field
            onInput={(e) => setFormValues({ remark: e.detail })}
            maxlength={300}
            showWordLimit
            placeholder='请给这次咨询打分'
            className=' p-4 bg-[#F6F7FB] block rounded-lg w-full mt-2'
          />

          <Button
            type='primary'
            block
            className=' mt-4'
            loading={loading}
            onClick={async () => {
              if (!formValues.rate)
                return Taro.showToast({ title: '请打分', icon: 'none' });
              if (!formValues.remark)
                return Taro.showToast({
                  title: '请输入您的评价',
                  icon: 'none',
                });

              //@ts-ignore
              await Taro.requestSubscribeMessage({
                tmplIds: [TemplateMessage.积分变动提醒],
              });

              await runAsync({
                id: props.detail.id,
                msg: formValues.remark,
                star: formValues.rate || 5,
              });
              props.onSuccess();
              setShow(false);
              Taro.showToast({ title: '提交成功' });
            }}
          >
            提交
          </Button>
        </View>
      </Popup>
    );
  }

  return {
    renderNode,
    open: () => setShow(true),
  };
}
